<template>
  <div class="bg-white dark:bg-zinc-900 xl:dark:bg-zinc-800 rounded pb-1">
    <div
      class="relative w-full rounded cursor-zoom-in group"
      :style="{ background: randomColor() }"
      @click="onPinsId"
    >
      <img
        ref="imageTarget"
        v-lazy
        class="w-full rounded bg-transparent"
        :src="data.photo"
        :style="{ height: (width / data.photoWidth) * data.photoHeight + 'px' }"
      />
      <div
        class="hidden opacity-0 w-full h-full bg-zinc-900/50 absoulte top-0 left-0 rounded duration-300 group-hover:opacity-100 xl:block"
      >
        <m-button class="absolute top-1.5 left-1.5">分享</m-button>
        <m-button
          class="absolute top-1.5 right-1.5"
          type="info"
          icon="heart"
          iconClass="fill-zinc-900 dark:fill-zinc-200"
        ></m-button>
        <m-button
          class="absolute bottom-1.5 left-1.5 bg-zinc-100/70"
          type="info"
          size="small"
          icon="download"
          @click="downloadImage"
          iconClass="fill-zinc-900 dark:fill-zinc-200"
        ></m-button>
        <m-button
          class="absolute bottom-1.5 right-1.5 bg-zinc-100/70"
          type="info"
          size="small"
          icon="full"
          @click="onImageFull"
          iconClass="fill-zinc-900 dark:fill-zinc-200"
        ></m-button>
      </div>
    </div>
    <!-- 标题 -->
    <p
      class="text-sm mt-1 font-bold text-zinc-900 dark:text-zinc -300 line-clamp-2 px-1"
    >
      {{ data.title }}
    </p>
    <!-- 作者 -->
    <div class="flex items-center mt-1 px-1">
      <img v-lazy class="h-2 w-2 rounded-full" :src="data.avatar" />
      <span class="text-sm text-zinc-500 ml-l">{{ data.author }}</span>
    </div>
  </div>
</template>
<script setup>
import { randomColor } from '@/utils/color'
import { saveAs } from 'file-saver'
import { message } from '@/libs/index.js'
import { ref, computed } from 'vue'
import { useFullscreen, useElementBounding } from '@vueuse/core'
const props = defineProps({
  data: {
    type: Object,
    require: true
  },
  width: {
    type: Number
  }
})

const downloadImage = () => {
  message('success', '图片开始下载')
  setTimeout(() => {
    saveAs(props.data.photo)
  }, 100)
}
const imageTarget = ref(null)
const { enter: onImageFull } = useFullscreen(imageTarget)
// 计算图片的中心点
const {
  x: imgContainerX,
  y: imgContainerY,
  width: imgContainerWidth,
  height: imgContainerHeight
} = useElementBounding(imageTarget)
const imgContainerCenter = computed(() => {
  return {
    translateX: parseInt(imgContainerWidth.value / 2 + imgContainerX.value),
    translateY: parseInt(imgContainerHeight.value / 2 + imgContainerY.value)
  }
})
const emits = defineEmits(['click'])
const onPinsId = () => {
  emits('click', { id: props.data.id, location: imgContainerCenter.value })
}
</script>
